//
//  DataHandle.m
//  Product_NEWS
//
//  Created by dllo on 16/1/9.
//  Copyright © 2016年 FCH. All rights reserved.
//

#import "DataHandle.h"

@implementation DataHandle
FMDatabase *db = nil;
//打开数据库
+ (void)openDataBase {
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] ;
    NSLog(@"%@",path);
    db = [FMDatabase databaseWithPath:[self getHomePath:@"CHENHAO.sqlite"]];
    if (![db open]) {
      
        
        
        return;
    }
    //为数据库设置缓存，提高性能
    [db setShouldCacheStatements:YES];
}

//创建收藏表

+ (void)createTable {
    //判断表是否创建
    [self openDataBase];
    [db executeUpdate:@"create table if not exists t_favorite(fchid integer primary key autoincrement, fchtitle text, fchurl text, fchdocid text, fchboardid text, flag text,skipTypeID text, skipID text)"];
    [db close];
}
//插入一条收藏信息
+ (BOOL)insertData:(FavoriteModel *)model {
    [self createTable];
    [self openDataBase];
    //处理为空
    if ([model.fchtitle isEqualToString:@""] || !model.fchtitle) {
        return NO;
    }
    FMResultSet *rs = [db executeQuery:@"select * from t_favorite where fchtitle=?", model.fchtitle];
    //已经存在
    if ([rs next]) {
        [rs close];
        [db close];
        return NO;
    } else {
        [db executeUpdate:@"insert into t_favorite(fchtitle, fchurl, fchdocid, fchboardid, flag,skipTypeID, skipID ) values(?, ?, ?, ?, ?,?,?)", model.fchtitle, model.fchurl, model.fchdocid, model.fchboardid, model.flag,model.skipTypeID,model.skipID];
        [db close];
        return YES;
    }
    
}
//删除一条收藏信息
+ (void)deleteData:(NSInteger)fchid {
    [self openDataBase];
    [db executeUpdate:@"delete from t_favorite where fchid=?",[NSString stringWithFormat:@"%ld", (long)fchid]];
    [db close];
}
//返回查询数据结果
+ (NSMutableArray *)getListData {
    [self createTable];
    [self openDataBase];
    NSMutableArray *listArr = [NSMutableArray array];
    FMResultSet *rs = [db executeQuery:@"select * from t_favorite"];
    while ([rs next]) {
        FavoriteModel *model = [[FavoriteModel alloc] init];
        model.fchid = [rs intForColumn:@"fchid"];
        model.fchtitle = [rs stringForColumn:@"fchtitle"];
        model.fchurl = [rs stringForColumn:@"fchurl"];
        model.fchboardid =  [rs stringForColumn:@"fchboardid"];
        model.fchdocid = [rs stringForColumn:@"fchdocid"];
        model.flag = [rs stringForColumn:@"flag"];
        model.skipTypeID = [rs stringForColumn:@"skipTypeID"];
        model.skipID = [rs stringForColumn:@"skipID"];
        
        
        
        
        [listArr addObject:model];
        [model release];
    }
    [rs close];
    [db close];
    return listArr;
}

+ (NSString *)getHomePath:(NSString *)databaseName {
    
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:databaseName];
    
    
}












@end
